package com.warom.sdg.ui.activity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Locale;

import android.util.Log;

import com.warom.sdg.R;
import com.warom.sdg.callback.PlcDataListener;
import com.warom.sdg.model.PlcDataEntity;
import com.warom.sdg.repository.PlcDataRepository;
import com.warom.sdg.util.J2modFix;
import com.warom.sdg.util.ModbusHelper;
import com.warom.sdg.util.PlcUnitMapper;

public class ModbusDemoActivity2 extends AppCompatActivity {

    private static final String TAG = "ModbusDemoActivity2";

    // 定义Modbus地址范围
    private static final int COIL_START = 1;             // 00001
    private static final int COIL_END = 9999;            // 09999
    private static final int DISCRETE_INPUT_START = 10001;
    private static final int DISCRETE_INPUT_END = 19999;
    private static final int INPUT_REGISTER_START = 30001;
    private static final int INPUT_REGISTER_END = 39999;
    private static final int HOLDING_REGISTER_START = 40001;
    private static final int HOLDING_REGISTER_END = 49999;

    private EditText etIpAddress, etPort;
    private EditText etReadAddress, etReadCount, etReadUnitId;
    private EditText etMultiAddresses;
    private EditText etWriteAddress, etWriteValue, etWriteUnitId;
    private Button btnConnect, btnDisconnect, btnRead, btnBatchRead, btnWrite;
    private Button btnWebView;
    private Button btnClearLog;
    private Button btnSaveToDb;  // 新增保存到数据库按钮
    private TextView tvLog;

    // 服务控制相关组件
    private Button btnStartService, btnStopService, btnSetInterval, btnAddMonitor, btnViewData;
    private EditText etPollInterval, etMonitorName, etMonitorAddress, etMonitorType;
    private TextView tvServiceStatus;

    private ModbusHelper modbusHelper;
    private boolean isConnected = false;

    // 添加数据库仓库引用
    private PlcDataRepository dataRepository;

    // 记录最近一次读取的数据和地址
    private String lastReadAddress = "";
    private String lastReadValue = "";
    private String lastReadType = "";

    // 修改为使用Map存储请求地址和原始地址映射
    private java.util.Map<Integer, String> requestAddressMap = new java.util.HashMap<>();
    // 添加一个计数器，用于生成唯一的请求ID
    private int requestIdCounter = 0;
    // 添加一个锁对象，用于同步访问Map和计数器
    private final Object requestMapLock = new Object();

    // PLC数据采集服务相关
    private boolean isServiceBound = false;
    private boolean isServiceRunning = false;

    // 服务连接
    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            isServiceBound = true;

            // 服务连接后更新UI
            updateServiceStatus();

            logMessage("PLC数据采集服务已连接");
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            isServiceBound = false;
            logMessage("PLC数据采集服务已断开连接");
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 初始化j2mod库修复
        J2modFix.init();

        // 初始化数据仓库
        dataRepository = new PlcDataRepository(this);

        setContentView(R.layout.activity_modbus_demo2);

        // 设置返回按钮
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setTitle("Modbus TCP PLC通信 (简化版)");
        }

        // 初始化控件
        initViews();

        // 设置按钮点击事件
        setupListeners();

        // 设置TextView可滚动
        tvLog.setMovementMethod(new android.text.method.ScrollingMovementMethod());

        // 添加触摸监听，阻止父ScrollView拦截TextView的滚动事件
        tvLog.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, android.view.MotionEvent event) {
                // 判断是否是垂直滚动操作
                boolean isScrolling = tvLog.canScrollVertically(1) || tvLog.canScrollVertically(-1);

                // 当用户触摸TextView且有滚动能力时，阻止父View拦截触摸事件
                v.getParent().requestDisallowInterceptTouchEvent(isScrolling);

                // 返回false让TextView自己处理触摸事件
                return false;
            }
        });

    }

    private void initViews() {
        etIpAddress = findViewById(R.id.et_ip_address);
        etPort = findViewById(R.id.et_port);
        etReadAddress = findViewById(R.id.et_read_address);
        etReadCount = findViewById(R.id.et_read_count);
        etReadUnitId = findViewById(R.id.et_read_unit_id);
        etMultiAddresses = findViewById(R.id.et_multi_addresses);
        etWriteAddress = findViewById(R.id.et_write_address);
        etWriteValue = findViewById(R.id.et_write_value);
        etWriteUnitId = findViewById(R.id.et_write_unit_id);

        btnConnect = findViewById(R.id.btn_connect);
        btnDisconnect = findViewById(R.id.btn_disconnect);
        btnRead = findViewById(R.id.btn_read);
        btnBatchRead = findViewById(R.id.btn_batch_read);
        btnWrite = findViewById(R.id.btn_write);
        btnWebView = findViewById(R.id.btn_webview);
        btnClearLog = findViewById(R.id.btn_clear_log);
        btnSaveToDb = findViewById(R.id.btn_save_to_db);  // 初始化保存到数据库按钮

        tvLog = findViewById(R.id.tv_log);

        // 初始化服务控制相关组件
        btnStartService = findViewById(R.id.btn_start_service);
        btnStopService = findViewById(R.id.btn_stop_service);
        btnSetInterval = findViewById(R.id.btn_set_interval);
        btnAddMonitor = findViewById(R.id.btn_add_monitor);
        btnViewData = findViewById(R.id.btn_view_data);

        etPollInterval = findViewById(R.id.et_poll_interval);
        etMonitorName = findViewById(R.id.et_monitor_name);
        etMonitorAddress = findViewById(R.id.et_monitor_address);
        etMonitorType = findViewById(R.id.et_monitor_type);

        tvServiceStatus = findViewById(R.id.tv_service_status);

        // 设置初始值
        etPort.setText("502"); // Modbus TCP默认端口
        etReadCount.setText("1");
        etReadUnitId.setText("1");
        etWriteUnitId.setText("1");
        etPollInterval.setText("5000"); // 默认5秒

        // 确保输入框能够正确响应
        setupEditTextInputHandling(etReadAddress);
        setupEditTextInputHandling(etWriteAddress);
        setupEditTextInputHandling(etReadCount);
        setupEditTextInputHandling(etWriteValue);
        setupEditTextInputHandling(etMultiAddresses);
        setupEditTextInputHandling(etPollInterval);
        setupEditTextInputHandling(etMonitorAddress);
    }

    // 设置EditText的输入处理
    private void setupEditTextInputHandling(EditText editText) {
        editText.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                Log.d(TAG, "EditText获取焦点: " + editText.getId());
            }
        });
    }

    private void setupListeners() {
        // 连接按钮
        btnConnect.setOnClickListener(v -> connectPLC());

        // 断开按钮
        btnDisconnect.setOnClickListener(v -> disconnectPLC());

        // 读取按钮
        btnRead.setOnClickListener(v -> readFromPLC());

        // 批量读取按钮
        btnBatchRead.setOnClickListener(v -> batchReadFromPLC());

        // 写入按钮
        btnWrite.setOnClickListener(v -> writeToPLC());

        // 保存到数据库按钮
        btnSaveToDb.setOnClickListener(v -> saveLastReadDataToDb());

        // WebView按钮
        btnWebView.setOnClickListener(v -> {
            Intent intent = new Intent(ModbusDemoActivity2.this, MainActivity.class);
            startActivity(intent);
            logMessage("跳转到WebView演示页面");
        });

        // 清除日志按钮
        btnClearLog.setOnClickListener(v -> {
            tvLog.setText("");
            logMessage("日志已清除");
        });


        btnAddMonitor.setOnClickListener(v -> addMonitorAddress());
        btnViewData.setOnClickListener(v -> viewPlcData());
    }

    private void connectPLC() {
        String ipAddress = etIpAddress.getText().toString().trim();
        String portStr = etPort.getText().toString().trim();

        if (TextUtils.isEmpty(ipAddress)) {
            showToast("请输入PLC的IP地址");
            return;
        }

        int port = 502; // 默认端口
        if (!TextUtils.isEmpty(portStr)) {
            try {
                port = Integer.parseInt(portStr);
            } catch (NumberFormatException e) {
                showToast("端口号格式不正确");
                return;
            }
        }

        logMessage("正在连接到 " + ipAddress + ":" + port + "...");

        // 禁用连接按钮，避免重复点击
        btnConnect.setEnabled(false);

        // 创建带地址感知的数据监听器
        AddressAwareDataListener listener = new AddressAwareDataListener(requestIdCounter, ipAddress + ":" + port);
        modbusHelper = new ModbusHelper(ipAddress, port, listener);

        // 在后台线程中连接
        new Thread(() -> {
            try {
                final boolean connected = modbusHelper.connect();
                runOnUiThread(() -> {
                    btnConnect.setEnabled(true); // 重新启用连接按钮

                    if (connected) {
                        isConnected = true;
                        updateConnectionStatus(true);
                        logMessage("连接成功");
                    } else {
                        isConnected = false;
                        updateConnectionStatus(false);
                        logMessage("连接失败，请检查IP地址和端口是否正确");
                    }
                });
            } catch (Exception e) {
                final String errorMsg = "连接过程发生异常: " + e.getMessage();
                Log.e(TAG, errorMsg, e);

                runOnUiThread(() -> {
                    btnConnect.setEnabled(true); // 重新启用连接按钮
                    isConnected = false;
                    updateConnectionStatus(false);
                    logMessage(errorMsg);
                    showToast("连接失败");
                });
            }
        }).start();
    }

    private void disconnectPLC() {
        if (modbusHelper != null) {
            modbusHelper.disconnect();
            isConnected = false;
            updateConnectionStatus(false);
            logMessage("已断开连接");
        }
    }

    private void readFromPLC() {
        if (!isConnected) {
            showToast("请先连接PLC");
            return;
        }

        String addressStr = etReadAddress.getText().toString().trim();
        String countStr = etReadCount.getText().toString().trim();
        String unitIdStr = etReadUnitId.getText().toString().trim();

        if (TextUtils.isEmpty(addressStr)) {
            showToast("请输入读取地址");
            return;
        }

        try {
            // 解析地址和类型
            ModbusAddressInfo addressInfo = parseModbusAddress(addressStr);
            if (addressInfo == null) {
                showToast("地址格式不正确，请输入完整的Modbus地址（如40001）");
                return;
            }

            int address = addressInfo.address;
            int count = TextUtils.isEmpty(countStr) ? 1 : Integer.parseInt(countStr);
            int unitId = TextUtils.isEmpty(unitIdStr) ? 1 : Integer.parseInt(unitIdStr);

            // 为此次请求生成唯一ID并保存原始地址
            int requestId;
            synchronized (requestMapLock) {
                requestId = requestIdCounter++;
                requestAddressMap.put(requestId, addressStr);
            }

            logMessage("读取 " + addressInfo.typeDescription + " 地址: " + addressStr +
                    " (协议地址: " + address + "), 数量: " + count + ", 单元ID: " + unitId);

            // 根据类型调用不同的读取函数
            switch (addressInfo.type) {
                case COIL:
                    modbusHelper.readBits(address, count, unitId, true);
                    break;
                case DISCRETE_INPUT:
                    modbusHelper.readBits(address, count, unitId, false);
                    break;
                case INPUT_REGISTER:
                    modbusHelper.readRegisters(address, count, unitId, true);
                    break;
                case HOLDING_REGISTER:
                    modbusHelper.readRegisters(address, count, unitId, false);
                    break;
            }
        } catch (NumberFormatException e) {
            showToast("数值格式不正确，请检查输入");
        } catch (Exception e) {
            logMessage("读取出错: " + e.getMessage());
            Log.e(TAG, "读取异常", e);
        }
    }

    private void writeToPLC() {
        if (!isConnected) {
            showToast("请先连接PLC");
            return;
        }

        String addressStr = etWriteAddress.getText().toString().trim();
        String valueStr = etWriteValue.getText().toString().trim();
        String unitIdStr = etWriteUnitId.getText().toString().trim();

        if (TextUtils.isEmpty(addressStr)) {
            showToast("请输入写入地址");
            return;
        }

        if (TextUtils.isEmpty(valueStr)) {
            showToast("请输入写入值");
            return;
        }

        try {
            // 解析地址和类型
            ModbusAddressInfo addressInfo = parseModbusAddress(addressStr);
            if (addressInfo == null) {
                showToast("地址格式不正确，请输入完整的Modbus地址（如40001或00001）");
                return;
            }

            int address = addressInfo.address;
            int unitId = TextUtils.isEmpty(unitIdStr) ? 1 : Integer.parseInt(unitIdStr);

            // 根据类型调用不同的写入函数
            switch (addressInfo.type) {
                case COIL:
                    boolean boolValue;
                    // 支持多种布尔值输入格式
                    if (valueStr.equalsIgnoreCase("true") || valueStr.equals("1")) {
                        boolValue = true;
                    } else if (valueStr.equalsIgnoreCase("false") || valueStr.equals("0")) {
                        boolValue = false;
                    } else {
                        showToast("线圈值必须是true/false或者1/0");
                        return;
                    }

                    logMessage("写入线圈 地址: " + addressStr + " (协议地址: " + address +
                            "), 值: " + boolValue + ", 单元ID: " + unitId);
                    modbusHelper.writeAddress(String.valueOf(address), boolValue, unitId);
                    break;

                case HOLDING_REGISTER:
                    // 对于寄存器，尝试解析整数值
                    int intValue;
                    try {
                        intValue = Integer.parseInt(valueStr);
                    } catch (NumberFormatException e) {
                        // 尝试解析十六进制
                        try {
                            if (valueStr.startsWith("0x") || valueStr.startsWith("0X")) {
                                intValue = Integer.parseInt(valueStr.substring(2), 16);
                            } else {
                                showToast("寄存器值必须是整数或十六进制数(0x开头)");
                                return;
                            }
                        } catch (NumberFormatException ex) {
                            showToast("寄存器值必须是整数");
                            return;
                        }
                    }

                    logMessage("写入寄存器 地址: " + addressStr + " (协议地址: " + address +
                            "), 值: " + intValue + " (0x" + Integer.toHexString(intValue) +
                            ", 二进制: " + Integer.toBinaryString(intValue) + "), 单元ID: " + unitId);
                    modbusHelper.writeSingleRegister(address, intValue, unitId);
                    break;

                case DISCRETE_INPUT:
                case INPUT_REGISTER:
                    showToast("输入寄存器和离散输入是只读的，不能写入");
                    break;
            }
        } catch (Exception e) {
            logMessage("写入出错: " + e.getMessage());
            Log.e(TAG, "写入异常", e);
        }
    }

    private void updateConnectionStatus(boolean connected) {
        btnConnect.setEnabled(!connected);
        btnDisconnect.setEnabled(connected);
        btnRead.setEnabled(connected);
        btnBatchRead.setEnabled(connected);
        btnWrite.setEnabled(connected);
        btnSaveToDb.setEnabled(connected);  // 更新保存按钮状态
    }

    // 创建自定义的ModbusHelper.PlcDataListener实现，包装原始接口
    private class AddressAwareDataListener implements PlcDataListener {
        private int requestId;
        private String originalAddress;

        public AddressAwareDataListener(int requestId, String originalAddress) {
            this.requestId = requestId;
            this.originalAddress = originalAddress;
        }

        @Override
        public void onDataReceived(Object data, String dataType,String plcDataA) {
            // 获取当前请求ID对应的原始地址
            String addressStr = "";
            synchronized (requestMapLock) {
                // 从Map中获取并移除最旧的请求
                if (!requestAddressMap.isEmpty()) {
                    // 获取最小的键（最早的请求）
                    Integer firstKey = java.util.Collections.min(requestAddressMap.keySet());
                    addressStr = requestAddressMap.remove(firstKey);
                }
            }

            // 保存最近一次读取的地址和数据，用于后续保存到数据库
            lastReadAddress = addressStr;

            // 记录数据类型
            if (dataType.contains("InputRegister")) {
                lastReadType = "输入寄存器";
            } else if (dataType.contains("HoldingRegister")) {
                lastReadType = "保持寄存器";
            } else if (dataType.contains("Coil")) {
                lastReadType = "线圈";
            } else if (dataType.contains("DiscreteInput")) {
                lastReadType = "离散输入";
            } else {
                lastReadType = dataType;
            }

            // 构建响应信息
            StringBuilder sb = new StringBuilder();

            // 显示地址信息
            if (!TextUtils.isEmpty(addressStr)) {
                sb.append("地址: ").append(addressStr).append(" - ");
            }

            sb.append("收到数据 (类型: ").append(dataType).append(")\n");

            if (data instanceof int[]) {
                int[] values = (int[]) data;
                sb.append("寄存器值: ").append(Arrays.toString(values)).append("\n");

                // 记录第一个值用于后续保存
                if (values.length > 0) {
                    lastReadValue = String.valueOf(values[0]);
                }

                // 添加十六进制和二进制表示
                for (int i = 0; i < values.length; i++) {
                    int value = values[i];
                    sb.append("值[").append(i).append("]: ")
                      .append(value).append(" (十进制), ")
                      .append("0x").append(Integer.toHexString(value)).append(" (十六进制), ")
                      .append(Integer.toBinaryString(value)).append(" (二进制)\n");
                }
            } else if (data instanceof boolean[]) {
                boolean[] values = (boolean[]) data;
                sb.append("位值: ").append(Arrays.toString(values));

                // 记录第一个值用于后续保存
                if (values.length > 0) {
                    lastReadValue = String.valueOf(values[0]);
                }
            } else {
                sb.append("原始数据: ").append(data.toString());
                lastReadValue = data.toString();
            }

            // 记录日志
            logMessage(sb.toString());

            // 启用保存按钮
            runOnUiThread(() -> btnSaveToDb.setEnabled(true));
        }



        @Override
        public void onError(String error) {
            logMessage("错误: " + error);
            lastReadAddress = "";
            lastReadValue = "";
            lastReadType = "";

            // 禁用保存按钮
            runOnUiThread(() -> btnSaveToDb.setEnabled(false));
        }
    }

    private void logMessage(String message) {
        String timestamp = new SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(new Date());
        String logMsg = timestamp + " - " + message;

        Log.d(TAG, logMsg);

        runOnUiThread(() -> {
            tvLog.append(logMsg + "\n\n");

            // 滚动到底部，使用post确保在布局完成后滚动
            tvLog.post(() -> {
                final int scrollAmount = tvLog.getLayout().getLineTop(tvLog.getLineCount()) - tvLog.getHeight();
                if (scrollAmount > 0) {
                    tvLog.scrollTo(0, scrollAmount);
                } else {
                    tvLog.scrollTo(0, 0);
                }
            });
        });
    }

    private void showToast(String message) {
        runOnUiThread(() -> Toast.makeText(this, message, Toast.LENGTH_SHORT).show());
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 断开Modbus连接
        if (modbusHelper != null) {
            modbusHelper.disconnect();
        }

        // 解绑服务
        if (isServiceBound) {
            try {
                unbindService(serviceConnection);
                isServiceBound = false;
            } catch (Exception e) {
                Log.e(TAG, "解绑服务时出错", e);
            }
        }
    }

    /**
     * 解析Modbus地址
     * 支持的格式：
     * - 00001-09999: 线圈
     * - 10001-19999: 离散输入
     * - 30001-39999: 输入寄存器
     * - 40001-49999: 保持寄存器
     */
    private ModbusAddressInfo parseModbusAddress(String addressStr) {
        try {
            int fullAddress = Integer.parseInt(addressStr);

            ModbusAddressInfo info = new ModbusAddressInfo();

            // 根据地址范围判断类型
            if (fullAddress >= COIL_START && fullAddress <= COIL_END) {
                info.type = ModbusRegisterType.COIL;
                info.address = fullAddress - 1; // Modbus协议地址从0开始
                info.typeDescription = "线圈";
                return info;
            } else if (fullAddress >= DISCRETE_INPUT_START && fullAddress <= DISCRETE_INPUT_END) {
                info.type = ModbusRegisterType.DISCRETE_INPUT;
                info.address = fullAddress - 10001; // 协议地址 = 实际地址 - 10001
                info.typeDescription = "离散输入";
                return info;
            } else if (fullAddress >= INPUT_REGISTER_START && fullAddress <= INPUT_REGISTER_END) {
                info.type = ModbusRegisterType.INPUT_REGISTER;
                info.address = fullAddress - 30001; // 协议地址 = 实际地址 - 30001
                info.typeDescription = "输入寄存器";
                return info;
            } else if (fullAddress >= HOLDING_REGISTER_START && fullAddress <= HOLDING_REGISTER_END) {
                info.type = ModbusRegisterType.HOLDING_REGISTER;
                info.address = fullAddress - 40001; // 协议地址 = 实际地址 - 40001
                info.typeDescription = "保持寄存器";
                return info;
            }

            return null; // 无效地址
        } catch (NumberFormatException e) {
            return null;
        }
    }

    /**
     * Modbus寄存器类型枚举
     */
    private enum ModbusRegisterType {
        COIL,               // 线圈
        DISCRETE_INPUT,     // 离散输入
        INPUT_REGISTER,     // 输入寄存器
        HOLDING_REGISTER    // 保持寄存器
    }

    /**
     * Modbus地址信息类
     */
    private class ModbusAddressInfo {
        ModbusRegisterType type;  // 寄存器类型
        int address;              // 协议地址（0-based）
        String typeDescription;   // 类型描述
    }

    /**
     * 批量读取多个PLC地址的数据
     */
    private void batchReadFromPLC() {
        if (!isConnected) {
            showToast("请先连接PLC");
            return;
        }

        String addressesStr = etMultiAddresses.getText().toString().trim();
        String unitIdStr = etReadUnitId.getText().toString().trim();

        if (TextUtils.isEmpty(addressesStr)) {
            showToast("请输入要读取的地址列表");
            return;
        }

        // 分割地址字符串
        String[] addressArray = addressesStr.split(",");
        if (addressArray.length == 0) {
            showToast("未找到有效的地址");
            return;
        }

        int unitId = TextUtils.isEmpty(unitIdStr) ? 1 : Integer.parseInt(unitIdStr);

        logMessage("开始批量读取 " + addressArray.length + " 个地址，单元ID: " + unitId);

        // 创建一个独立线程进行批量读取，避免阻塞UI线程
        new Thread(() -> {
            // 遍历每个地址
            for (String address : addressArray) {
                try {
                    String trimmedAddress = address.trim();
                    if (trimmedAddress.isEmpty()) {
                        continue;
                    }

                    // 解析单个地址
                    ModbusAddressInfo addressInfo = parseModbusAddress(trimmedAddress);
                    if (addressInfo == null) {
                        logMessage("无效地址: " + trimmedAddress + "，跳过");
                        continue;
                    }

                    // 为此次请求生成唯一ID并保存原始地址
                    int requestId;
                    synchronized (requestMapLock) {
                        requestId = requestIdCounter++;
                        requestAddressMap.put(requestId, trimmedAddress);
                    }

                    // 执行读取操作
                    logMessage("读取地址: " + trimmedAddress + " (" + addressInfo.typeDescription +
                            ", 协议地址: " + addressInfo.address + ")");

                    // 根据类型调用不同的读取函数
                    switch (addressInfo.type) {
                        case COIL:
                            modbusHelper.readBits(addressInfo.address, 1, unitId, true);
                            break;
                        case DISCRETE_INPUT:
                            modbusHelper.readBits(addressInfo.address, 1, unitId, false);
                            break;
                        case INPUT_REGISTER:
                            modbusHelper.readRegisters(addressInfo.address, 1, unitId, true);
                            break;
                        case HOLDING_REGISTER:
                            modbusHelper.readRegisters(addressInfo.address, 1, unitId, false);
                            break;
                    }

                    // 给PLC一些响应时间，避免连续请求过快
                    Thread.sleep(100);

                } catch (Exception e) {
                    logMessage("读取地址 " + address + " 时出错: " + e.getMessage());
                    Log.e(TAG, "批量读取异常", e);
                }
            }

            logMessage("批量读取完成");

        }).start();
    }







    // 添加监控地址
    private void addMonitorAddress() {
        if (!isServiceBound) {
            showToast("服务未连接，无法添加监控地址");
            return;
        }

        String name = etMonitorName.getText().toString().trim();
        String address = etMonitorAddress.getText().toString().trim();
        String type = etMonitorType.getText().toString().trim();

        if (TextUtils.isEmpty(name) || TextUtils.isEmpty(address) || TextUtils.isEmpty(type)) {
            showToast("请填写完整的监控地址信息");
            return;
        }

        // 验证地址格式
        try {
            int fullAddress = Integer.parseInt(address);
            if (fullAddress < 1 || fullAddress > 49999) {
                showToast("无效的Modbus地址");
                return;
            }
        } catch (NumberFormatException e) {
            showToast("地址必须是数字");
            return;
        }

        // 创建地址配置
        int unitId = 1;
        try {
            unitId = Integer.parseInt(etReadUnitId.getText().toString().trim());
        } catch (NumberFormatException e) {
            // 使用默认值
        }



        // 添加到服务
        // 如果需要，可以在这里添加添加监控地址的逻辑
        logMessage("已添加监控地址: " + name + " (" + address + ")" + " (单元ID: " + unitId + ")");

        // 清空输入框
        etMonitorName.setText("");
        etMonitorAddress.setText("");
        etMonitorType.setText("");
    }

    // 查看PLC历史数据
    private void viewPlcData() {
        try {
            // 创建查看历史数据的Intent
            Intent intent = new Intent(this, PlcDataViewActivity.class);
            startActivity(intent);
        } catch (Exception e) {
            Log.e(TAG, "启动数据查看界面失败", e);
            showToast("启动数据查看界面失败: " + e.getMessage());
        }
    }



    // 更新服务状态显示
    private void updateServiceStatus() {
        runOnUiThread(() -> {
            if (isServiceRunning) {
                tvServiceStatus.setText("服务状态: 运行中");
                btnStartService.setEnabled(false);
                btnStopService.setEnabled(true);
                btnSetInterval.setEnabled(true);
                btnAddMonitor.setEnabled(true);
            } else {
                tvServiceStatus.setText("服务状态: 未运行");
                btnStartService.setEnabled(true);
                btnStopService.setEnabled(false);
                btnSetInterval.setEnabled(false);
                btnAddMonitor.setEnabled(false);
            }
        });
    }

    // 保存最近读取的数据到数据库
    private void saveLastReadDataToDb() {
        if (TextUtils.isEmpty(lastReadAddress) || TextUtils.isEmpty(lastReadValue)) {
            showToast("没有可保存的数据，请先读取PLC数据");
            return;
        }

        // 创建一个数据点名称（如果为空，使用地址作为名称）
        String name = etMonitorName.getText().toString().trim();
        if (TextUtils.isEmpty(name)) {
            name = "PLC数据点-" + lastReadAddress;
        }

        // 创建数据类型（如果为空，根据地址类型生成）
        String type = etMonitorType.getText().toString().trim();
        if (TextUtils.isEmpty(type)) {
            if (lastReadType.contains("寄存器")) {
                type = "数值";
            } else if (lastReadType.contains("线圈") || lastReadType.contains("离散")) {
                type = "开关量";
            } else {
                type = "未知类型";
            }
        }

        // 使用映射工具自动确定单位
        String unit = PlcUnitMapper.determineUnit(lastReadAddress, type);

        // 创建数据实体
        PlcDataEntity data = new PlcDataEntity();
        data.setDeviceId(1); // 设置默认设备ID为1，实际项目中应使用已连接的设备ID
        data.setName(name);
        data.setAddress(lastReadAddress);
        data.setType(type);
        data.setValue(lastReadValue);
        data.setUnit(unit);
        data.setTimestamp(System.currentTimeMillis());
        // 设置时间字符串
        data.updateTimeString();

        // 保存到数据库
        String displayUnit = unit.isEmpty() ? "" : " " + unit;
        dataRepository.insert(data,
            // 成功回调
            () -> {
                logMessage("已保存数据到数据库: 设备ID=1, 地址=" + lastReadAddress + ", 值=" + lastReadValue + displayUnit);
                showToast("数据已保存到数据库");
            },
            // 错误回调
            error -> {
                logMessage("保存数据失败: " + error);
                showToast("保存数据失败: " + error);
            }
        );
    }
}